<?php

namespace app\domain\admin;

use app\model\DeviceData;

class DashBoardDomain extends CommonDomain
{
    public function dashboard(): array
    {
        try {
            $dataTotal = app(DeviceData::class)->count();
            $timestamp = time();
            $lastDay = strtotime("-1 day", $timestamp);
            $monthCondition = [$lastDay, $timestamp];

            $currentMonth = strtotime(date('Y-m', $timestamp));
            $dataTotalMonth = app(DeviceData::class)->whereTime('receive_time', 'between', [$currentMonth, $timestamp])->count();

            $deviceDataList = app(DeviceData::class)
                ->withoutField(['original_data'])
                ->whereTime('receive_time', 'between', $monthCondition)
                ->order('id DESC')
                ->select();

            $guangdian = $fengdian = $yadian = [];
            $lastData = null;
            $deviceDataList->filter(function ($row) use (&$guangdian, &$fengdian, &$yadian, &$lastData) {
                if (isset($lastData)) {
                    if (800 < abs($lastData['guangdian'] - $row['guangdian'])) {
                        $guangdian['date'][] = $row['receive_time'];
                        $guangdian['data'][] = $row['guangdian'];
                    }


                    if (10000 < abs($lastData['fengdian'] - $row['fengdian'])) {
                        $fengdian['date'][] = $row['receive_time'];
                        $fengdian['data'][] = $row['fengdian'];
                    }

                    if (2000 < abs($lastData['yadian'] - $row['yadian'])) {
                        $yadian['date'][] = $row['receive_time'];
                        $yadian['data'][] = $row['yadian'];
                    }
                }
                $lastData = $row;
            });

            $guangdian['date'] = array_reverse($guangdian['date']);
            $guangdian['data'] = array_reverse($guangdian['data']);

            $fengdian['date'] = array_reverse($fengdian['date']);
            $fengdian['data'] = array_reverse($fengdian['data']);

            $yadian['date'] = array_reverse($yadian['date']);
            $yadian['data'] = array_reverse($yadian['data']);

            return [
                'dataTotal' => $dataTotal,
                'dataTotalMonth' => $dataTotalMonth,
                'guangdian' => $guangdian,
                'fengdian' => $fengdian,
                'yadian' => $yadian,
            ];
        } catch (\Exception $e) {
            return [];
        }
    }
}